package com.scmagic.braintree_payments;

import com.braintreepayments.api.BraintreeFragment;
import com.braintreepayments.api.PayPal;
import com.braintreepayments.api.exceptions.InvalidArgumentException;
import com.braintreepayments.api.interfaces.BraintreeCancelListener;
import com.braintreepayments.api.interfaces.BraintreeErrorListener;
import com.braintreepayments.api.interfaces.BraintreeListener;
import com.braintreepayments.api.interfaces.PaymentMethodNonceCreatedListener;
import com.braintreepayments.api.models.PayPalRequest;
import com.braintreepayments.api.models.PaymentMethodNonce;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;

/** BraintreePaymentsPlugin */
public class BraintreePaymentsPlugin implements MethodCallHandler {
  /** Plugin registration. */
  public static void registerWith(Registrar registrar) {
    final MethodChannel channel = new MethodChannel(registrar.messenger(), "braintree_payments");
    channel.setMethodCallHandler(new BraintreePaymentsPlugin(registrar));
  }

  BraintreePaymentsPlugin(Registrar _registrar) {
      registrar = _registrar;
  }

  BraintreeFragment braintreeFragment;
  Registrar registrar;

  @Override
  public void onMethodCall(MethodCall call, final Result result) {
    if (call.method.equals("pay")) {
        String token = call.argument("token");
        String amount = call.argument("amount");
        String currency = call.argument("currency");

        try {
            braintreeFragment = BraintreeFragment.newInstance(registrar.activity(), token);

            PayPalRequest request = new PayPalRequest(amount)
                    .currencyCode(currency)
                    .intent(PayPalRequest.INTENT_AUTHORIZE);
            PayPal.requestOneTimePayment(braintreeFragment, request);
        } catch (InvalidArgumentException e) {
            result.error("错误", "初始化", e);
        }

        braintreeFragment.addListener(new PaymentMethodNonceCreatedListener() {
            @Override
            public void onPaymentMethodNonceCreated(PaymentMethodNonce paymentMethodNonce) {
                braintreeFragment.removeListener(this);
                result.success(paymentMethodNonce.getNonce());
            }
        });

        braintreeFragment.addListener(new BraintreeCancelListener() {
            @Override
            public void onCancel(int requestCode) {
                braintreeFragment.removeListener(this);
                result.error("错误", "取消", requestCode);
            }
        });

        braintreeFragment.addListener(new BraintreeErrorListener() {
            @Override
            public void onError(Exception error) {
                result.error("错误", "异常", error);
            }
        });
    } else {
      result.notImplemented();
    }
  }
}
